var Login = function($, undefined){
	var win=null,	
		submit = function(u, p){
			if (typeof u === 'object' || typeof u === 'undefined') u = win.content.find('.input[name=username]').val() || '';
			if (typeof p === 'undefined') p = win.content.find('.input[name=password]').val() || '';		
			
			$.ajax({ url: 'login', data: { username: u, password: p }, type: 'post' })
			.error(function(data){
				if (localStorage){
					delete localStorage.u;
					delete localStorage.h;
				}
				location.reload(); 
			})
			.success(function(data){ 	
				if (!data || data.result == 'error') {
					if (localStorage){
						delete localStorage.u;
						delete localStorage.h;
					}
					msgerror(data.msg);
				}
				else {
					if (localStorage){
						localStorage.u = u;
						localStorage.h = data.hash;
					}
					location.reload(); 
				}
			});
		},
		
		init = function(){
			if (localStorage && localStorage.u && localStorage.h){
				submit(localStorage.u, localStorage.h);																	// creds. saved - use them
				return;
			}
	
			if ($('.login-window').length) return;																		// login win is visible
			
			win = new Window({ disposable: true, renderCloser: false, cls: 'login-window', closable: false,				// show login window 
				content:'<label class="label">Username</label><input class="input" name="username" autofocus>'+
						'<label class="label">Password</label><input class="input" type="password" name="password">'+
						'<a class="login-button" title="Login" href="#"></a>'
			}).show();
			
			win.content
				.on('click', '.login-button', submit)
				.on('keypress', 'input', function(e){ if (e.which == 13) submit(); });
		};
	
	
	return {
		init: init
	};
}(jQuery);